'use strict';

/**
 * Copyright @2016-present, Sumscope, Inc.
 * All rights reserved.
 */

const fetchApi = require('node-fetch');

class Http {
  
  constructor() {
    this.urls = {};
    this.urls.default = 'http://localhost:8080';
  }
  
  setDefault(url) {
    this.urls.default = url;
  }
  
  setAlias(tag, url) {
    this.urls[tag] = url;
  }
  
  setAgent(agent) {
    this.agent = agent;
  }
  
  fetch(api, options, req) {
    if (req && req.session.user !== undefined) {
      options.headers['UserToken'] = req.session.user.id;
    }
    return this.fetchUrl(this.urls.default, api, options, req);
  }
  
  fetchAlias(alias, api, options, req) {
    if (req && req.session.user !== undefined) {
      options.headers['UserToken'] = req.session.user.id;
    }
    return this.fetchUrl(this.urls[alias], api, options, req);
  }
  
  fetchUrl(host, api, options) {
    if (this.agent) {
      options.agent = this.agent;
    }
    return fetchApi(host + api, options)
      .then(res => res.json());
  }
  
  get(api, req) {
    return this.fetch(api, {
      method: 'get',
      headers: {
        'Accept': 'application/json'
      }
    }, req);
  }
  
  getAlias(alias, api, req) {
    return this.fetchAlias(alias, api, {
      method: 'get',
      headers: {
        'Accept': 'application/json'
      }
    }, req);
  }
  
  post(api, body, req) {
    return this.fetch(api, {
      method: 'post',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json; charset=utf-8'
      },
      body: JSON.stringify(body)
    }, req);
  }
  
  postAlias(alias, api, body, req) {
    return this.fetchAlias(alias, api, {
      method: 'post',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json; charset=utf-8'
      },
      body: JSON.stringify(body)
    }, req);
  }
  
  
  postForm(api, body, req) {
    const formData = [];
    for (const prop in body) {
      formData.push(`${prop}=${body[prop]}`);
    }
    return this.fetch(api, {
      method: 'post',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
      },
      body: formData.join('&')
    }, req);
  }
  
  toUrl(host, port) {
    let url = 'http://' + host;
    if (port && port !== '') {
      url += ':' + port;
    }
    return url;
  }
}

module.exports = exports = new Http();
